"use client";

import React, { useState, useEffect } from "react";
import {
  HeartOutlined,
  StarOutlined,
  LeftOutlined,
  EditOutlined,
  FlagOutlined,
  HomeOutlined,
  MessageOutlined,
} from "@ant-design/icons";
import { Card, Button, Typography, message, Avatar, Tabs } from "antd";
import { useRouter, useParams } from "next/navigation";
import { useUser } from "../../context/userContext";
import api from "../../utils/api";
import Comments from "./comments";
import Link from "next/link";
import fontStyle from "@/components/Font.module.css";

const { Title, Text } = Typography;
const { TabPane } = Tabs;

export default function PostPage() {
  const [post, setPost] = useState(null);
  const [likes, setLikes] = useState(0);
  const [isLiked, setIsLiked] = useState(false);
  const [favorites, setFavorites] = useState(0);
  const [isFavorited, setIsFavorited] = useState(false);
  const [author, setAuthor] = useState(null);
  const [authorIcon, setAuthorIcon] = useState("");
  const [loading, setLoading] = useState(true);
  const router = useRouter();
  const { user } = useUser();
  const { postId } = useParams();

  useEffect(() => {
    if (postId) {
      fetchPost();
    }
  }, [postId, user]);

  const fetchPost = async () => {
    try {
      setLoading(true);

      const headers = user?.access_token
        ? { Authorization: `Bearer ${user.access_token}` }
        : {};

      const response = await api.get("/posts/detail", {
        params: { id: postId, _: Date.now() },
        headers,
      });

      if (response.status === 200) {
        const postData = response.data;
        setPost(postData);
        setLikes(postData.likes || 0);
        setFavorites(postData.favourites || 0);
        setIsLiked(postData.isLikedByCurrentUser);
        setIsFavorited(postData.isfavouritedByCurrentUser);

        // 获取作者信息
        const authorResponse = await api.get("/users/info", {
          params: { id: postData.authorId },
        });

        if (authorResponse.status === 200) {
          setAuthor(authorResponse.data);
          setAuthorIcon(authorResponse.data.icon);
        }
      }
    } catch (error) {
      console.error("获取帖子或作者信息失败:", error);
      message.error("加载帖子失败，请稍后重试");
      router.push("/404");
    } finally {
      setLoading(false);
    }
  };

  const handleLike = async () => {
    if (!postId) return;
    try {
      const headers = user?.access_token
        ? { Authorization: `Bearer ${user.access_token}` }
        : {};

      const response = await api.post(
        `/posts/like?postId=${postId}`,
        {},
        { headers }
      );

      if (response.status === 200 || response.status === 201) {
        await fetchPost();
        message.success("点赞成功");
      }
    } catch (error) {
      if (error.response?.status === 409) {
        message.warning("已经点赞过");
      } else {
        message.error("点赞失败，请稍后重试");
      }
    }
  };

  const handleUnlike = async () => {
    if (!postId) return;
    try {
      const headers = user?.access_token
        ? { Authorization: `Bearer ${user.access_token}` }
        : {};

      const response = await api.post(
        `/posts/unlike?postId=${postId}`,
        {},
        { headers }
      );

      if (response.status === 200 || response.data.success === true) {
        await fetchPost();
        message.success("取消点赞成功");
      }
    } catch (error) {
      message.error("取消点赞失败，请稍后重试");
    }
  };

  const handleFavorite = async () => {
    if (!postId) return;
    try {
      const headers = user?.access_token
        ? { Authorization: `Bearer ${user.access_token}` }
        : {};
      const response = await api.post(
        `/posts/favourite?postId=${postId}`,
        {},
        { headers }
      );
      if (response.data.success === true) {
        await fetchPost();
        message.success("收藏成功");
      }
    } catch (error) {
      if (error.response?.status === 409) {
        message.warning("已经收藏过");
      } else {
        message.error("收藏失败，请稍后重试");
      }
    }
  };

  const handleUnfavorite = async () => {
    if (!postId) return;
    try {
      const headers = user?.access_token
        ? { Authorization: `Bearer ${user.access_token}` }
        : {};
      const response = await api.post(
        `/posts/unfavourite?postId=${postId}`,
        {},
        { headers }
      );
      if (response.data.success === true) {
        await fetchPost();
        message.success("取消收藏成功");
      }
    } catch (error) {
      message.error("取消收藏失败，请稍后重试");
    }
  };

  const handleBack = () => {
    router.back();
  };

  if (loading || !post) {
    return (
      <div
        style={{
          display: "flex",
          justifyContent: "center",
          alignItems: "center",
          height: "100vh",
        }}
      >
        <div className="text-center">
          <div className="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-[#D6A7A1] mb-4"></div>
          <p className="text-[#7A6E6E] text-lg">加载中...</p>
        </div>
      </div>
    );
  }

  return (
    <div
      style={{
        display: "flex",
        flexDirection: "column",
        alignItems: "center",
        minHeight: "100vh",
        padding: "20px",
        background: "linear-gradient(135deg, #F4EDEB 0%, #F0E6E2 100%)",
        position: "relative",
        overflow: "hidden",
      }}
    >
      {/* 背景气泡装饰 */}
      <div className="absolute inset-0 overflow-hidden pointer-events-none">
        <div className="absolute top-[10%] left-[5%] w-32 h-32 bg-[#D6A7A1]/10 rounded-full animate-float" />
        <div className="absolute top-[25%] right-[15%] w-24 h-24 bg-[#D6A7A1]/15 rounded-full animate-float-delay-1" />
        <div className="absolute bottom-[20%] left-[10%] w-40 h-40 bg-[#D6A7A1]/10 rounded-full animate-float-delay-2" />
        <div className="absolute bottom-[30%] right-[5%] w-28 h-28 bg-[#D6A7A1]/15 rounded-full animate-float-delay-3" />
      </div>

      {/* 页面顶部操作栏 */}
      <div
        style={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          width: "72%",
          maxWidth: "1200px",
          boxSizing: "border-box",
          zIndex: 10,
        }}
      >
        {/* 左侧图标区 */}
        <div style={{ display: "flex", alignItems: "center", gap: "16px" }}>
          {/* 回到主页图标 */}
          <div
            style={{
              fontSize: 30,
              color: "#7A6E6E",
              cursor: "pointer",
              transition: "color 0.3s",
            }}
            onClick={() => router.push("/homepage/home")}
            className="hover:text-[#D6A7A1]"
          >
            <HomeOutlined />
          </div>

          {/* 返回图标 */}
          <div
            style={{
              fontSize: 30,
              color: "#7A6E6E",
              cursor: "pointer",
              transition: "color 0.3s",
            }}
            onClick={handleBack}
            className="hover:text-[#D6A7A1]"
          >
            <LeftOutlined />
          </div>
        </div>

        {/* 右侧图标区 */}
        <div style={{ display: "flex", alignItems: "center", gap: "16px" }}>
          {/* 编辑或举报按钮 - 根据用户角色显示不同内容 */}
          {user && user.id === post.authorId ? (
            // 作者看到编辑按钮
            <Link href={`/posts/${postId}/edit`}>
              <div
                style={{
                  fontSize: 30,
                  color: "#7A6E6E",
                  cursor: "pointer",
                  transition: "color 0.3s",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  width: 48,
                  height: 48,
                  borderRadius: 24,
                  background: "white",
                  boxShadow: "0 2px 8px rgba(0, 0, 0, 0.1)",
                }}
                className="hover:bg-[#F4EDEB] hover:text-[#D6A7A1]"
              >
                <EditOutlined />
              </div>
            </Link>
          ) : (
            // 非作者看到举报按钮
            <Link href={`/posts/${postId}/report`}>
              <div
                style={{
                  fontSize: 30,
                  color: "#d9534f",
                  cursor: "pointer",
                  transition: "color 0.3s",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  width: 48,
                  height: 48,
                  borderRadius: 24,
                  background: "white",
                  boxShadow: "0 2px 8px rgba(0, 0, 0, 0.1)",
                }}
                className="hover:bg-[#F4EDEB] hover:text-[#E57373]"
              >
                <FlagOutlined />
              </div>
            </Link>
          )}
        </div>
      </div>

      <Card
        style={{
          width: "90%",
          maxWidth: 1100,
          height: "88vh",
          background: "white",
          border: "none",
          borderRadius: 20,
          margin: "10px auto",
          boxShadow: "0 4px 20px rgba(0, 0, 0, 0.08)",
          overflow: "hidden",
          position: "relative",
          zIndex: 1,
        }}
      >
        {/* 帖子标题和作者信息 */}
        <div style={{ padding: "20px 24px 0" }}>
          <div
            className={fontStyle.titlesmall}
            style={{
              marginTop: "-20px",
              fontSize: "32px",
              marginBottom: "20px",
            }}
          >
            {post.title}
          </div>

          <div
            style={{
              display: "flex",
              alignItems: "center",
              marginBottom: "20px",
            }}
          >
            <Avatar
              src={`http://120.26.138.4:3000${authorIcon}`}
              size={40}
              style={{
                marginRight: 16,
                boxShadow: "0 2px 8px rgba(0, 0, 0, 0.1)",
              }}
            />
            <div>
              <Link href={`/author/${post.authorId}`}>
                <span
                  className={fontStyle.linkText}
                  style={{ fontSize: "20px" }}
                >
                  {author?.display_name || "未知用户"}
                </span>
              </Link>
              <Text
                type="secondary"
                className={fontStyle.text}
                style={{
                  marginLeft: "16px",
                  fontSize: "14px",
                }}
              >
                {new Date(post.createdAt).toLocaleString()}
              </Text>
            </div>
          </div>
        </div>

        {/* 帖子内容 */}
        <div style={{ padding: "0 24px 20px" }}>
          {/* 帖子正文 */}
          <div
            className={fontStyle.text}
            style={{
              height: "12vh", // 显示固定高度
              overflowY: "auto", // 内容超过时显示滚动条
              lineHeight: "1.6",
              paddingRight: "6px", // 防止滚动条遮挡文字
              marginBottom: "28px",
              whiteSpace: "pre-wrap", // 保证换行格式不丢失
            }}
          >
            {post.content}
          </div>

          {/* 帖子标签 */}
          <div
            style={{
              display: "flex",
              flexWrap: "wrap",
              gap: 8,
            }}
          >
            {post.tagNames.length > 0 && (
              <span className={fontStyle.text}> 标签:</span>
            )}
            {post.tagNames.map((tagName, index) => (
              <Link
                key={index}
                href={`/tags/${tagName}`}
                style={{
                  backgroundColor: "#F4EDEB",
                  color: "#D6A7A1",
                  padding: "4px 12px",
                  borderRadius: 16,
                  fontSize: "14px",
                  textDecoration: "none",
                  transition: "all 0.3s",
                }}
                className="hover:bg-[#F0E6E2] hover:shadow-sm"
              >
                {tagName}
              </Link>
            ))}
          </div>

          {/* 互动按钮 */}
          <div
            style={{
              marginTop: "10px",
              display: "flex",
              alignItems: "center",
              gap: 24,
            }}
          >
            <Button
              onClick={isLiked ? handleUnlike : handleLike}
              style={{
                border: "none",
                backgroundColor: "transparent",
                color: isLiked ? "#D6A7A1" : "#7A6E6E",
                fontSize: "16px",
                display: "flex",
                alignItems: "center",
                transition: "color 0.3s",
                padding: 0,
              }}
              className="hover:text-[#D6A7A1]"
            >
              <HeartOutlined style={{ marginRight: 4, fontSize: "18px" }} />
              <span>{likes}</span>
            </Button>

            <Button
              onClick={isFavorited ? handleUnfavorite : handleFavorite}
              style={{
                border: "none",
                backgroundColor: "transparent",
                color: isFavorited ? "#D6A7A1" : "#7A6E6E",
                fontSize: "16px",
                display: "flex",
                alignItems: "center",
                transition: "color 0.3s",
                padding: 0,
              }}
              className="hover:text-[#D6A7A1]"
            >
              <StarOutlined style={{ marginRight: 4, fontSize: "18px" }} />
              <span>{favorites}</span>
            </Button>
          </div>
        </div>

        {/* 评论区 */}
        <div style={{ padding: "0px 20px" }}>
          <Comments postId={postId} />
        </div>
      </Card>
    </div>
  );
}
